var log4js = require("log4js");
var path = require("path");
var fs = require("fs");
var basePath = path.resolve(__dirname, "../logs");

var errorPath = basePath + "/errors/";
var resPath = basePath + "/responses/";

var errorFilename = errorPath + "/error";
var resFilename = resPath + "/response";

/**
 * 确定目录是否存在，如果不存在则创建目录
 */
var confirmPath = function (pathStr) {
  if (!fs.existsSync(pathStr)) {
    fs.mkdirSync(pathStr);
    console.log("createPath: " + pathStr);
  }
};
log4js.configure({
  appenders: {  //输出源
    error: {
      category: 'errorLogger', // logger 名称
      type: 'dateFile', // 日志类型
      filename: errorFilename, // 日志输出位置
      encoding: "utf-8",
      alwaysIncludePattern: true, // 是否有后缀名
      pattern: 'yyyy-MM-dd-hh.log', // 后缀 每一小时创建一个新的日志文件
    },
    response: {
      category: 'responseLogger',
      type: 'dateFile',
      filename: resFilename,
      alwaysIncludePattern: true,
      pattern: 'yyyy-MM-dd-hh.log'
    }

  },
  // ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < MARK < OFF
  "categories": {//类别
    "error": {
      "appenders": [
        "error"
      ],
      "level": "error"
    },
    "response": {
      "appenders": [
        "response"
      ],
      "level": "info"
    },
    "default": {
      "appenders": [  //当指定level为INFO时，只允许输出INFO级别以上的日志，WARN、ERROR都会被记录，但是TRACE和DEBUG不会
        "error",
        "response"
      ],
      "level": "debug"
    },

  },
  pm2: true,
  pm2InstanceVar: 'INSTANCE_ID',
  disableClustering: true
});
//创建log的根目录'logs'
if (basePath) {
  confirmPath(basePath);
  //根据不同的logType创建不同的文件目录
  confirmPath(errorPath);
  confirmPath(resPath);
}

module.exports = {
    install: async app => {
        app.use((req, res, next)=>{
            req.log = log4js.getLogger("response");
            req.log.error(`使用${req.method}请求访问${req.url}, 携带参数query:${JSON.stringify(req.query)}, body:${JSON.stringify(req.body)}`)
            next();
        });
        return
    }
};